<template>
  <div class="app-container">
    <el-card shadow="never" class="mb16" header="基本信息">
      <el-form :model="form" :rules="basicRules" ref="basicFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="资产编号" prop="assetNo">
              <el-input v-model="form.assetNo" placeholder="请选择" :readonly="true" />
              <el-button type="primary" size="mini" style="margin-top:6px" @click="openAssetSelector">选择资产</el-button>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择" filterable clearable style="width:100%" disabled>
                <el-option v-for="it in equipmentTypes" :key="it.code" :label="it.name" :value="it.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="名称" prop="assetName">
              <el-input v-model="form.assetName" placeholder="请选择" readonly />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="使用部门" prop="deptId">
              <el-input v-model="form.deptId" placeholder="请选择" readonly />
            </el-form-item>
          </el-col>
          <el-col :lg="16" :md="24" :sm="24">
            <el-form-item label="位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入" readonly />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="mb16" header="故障信息">
      <el-form :model="form" :rules="rules" ref="faultFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="发生时间" prop="occurTime">
              <el-date-picker
                v-model="form.occurTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                @change="handleOccurTimeChange" />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="报修人" prop="reporter">
              <el-input v-model="form.reporter" readonly />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="紧急程度" prop="urgency">
              <el-select v-model="form.urgency" placeholder="请选择" clearable filterable style="width:100%">
                <el-option v-for="lv in urgencyLevels" :key="lv.code" :label="lv.name" :value="lv.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="报修类型" prop="reportType">
              <el-select v-model="form.reportType" placeholder="请选择" clearable filterable style="width:100%">
                <el-option v-for="rt in reportTypes" :key="rt.code" :label="rt.name" :value="rt.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="12" :sm="24">
            <el-form-item label="故障类型" prop="faultType">
              <el-select v-model="form.faultType" placeholder="请选择" clearable filterable style="width:100%">
                <el-option v-for="ft in faultTypes" :key="ft.code" :label="ft.name" :value="ft.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="24" :md="24" :sm="24">
            <el-form-item label="故障描述" prop="description">
              <el-input type="textarea" :rows="3" v-model="form.description" resize="none"/>
            </el-form-item>
          </el-col>
          <el-col :lg="24" :md="24" :sm="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :rows="2" v-model="form.remark" resize="none"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" header="故障图片">
      <image-upload ref="imageUpload" v-model="images" :limit="5" />
    </el-card>

    <div class="dialog-footer" style="margin-top:16px;text-align:right;">
      <el-button @click="goBack">返回</el-button>
      <el-button @click="tempSave">临时保存</el-button>
      <el-button v-if="draftExists" @click="restoreDraft">恢复草稿</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <!-- 资产选择弹窗 -->
    <el-dialog title="选择资产" :visible.sync="selectorVisible" width="900px">
      <asset-selector :selected-assets="selectedAssets" :multiple="false" :onlyAbnormal="false" @confirm="onSelectAssets" @close="selectorVisible=false" />
    </el-dialog>
  </div>
</template>

<script>
import { addOrder, getOrder, updateOrder } from '@/api/repair/order'
import request from '@/utils/request'
import { getAsset } from '@/api/asset/asset'
import { getDept } from '@/api/system/dept'
import ImageUpload from '@/views/components/ImageUpload.vue'
import AssetSelector from '@/views/components/AssetSelector.vue'
import { loadRepairDictionaries } from '@/utils/dictionary'
import store from '@/store'

export default {
  name: 'OrderForm',
  components: { ImageUpload, AssetSelector },
  data() {
    return {
      form: {
        reportNo: undefined,
        assetNo: undefined,
        type: undefined,
        assetName: undefined,
        deptId: undefined,
        location: undefined,
        occurTime: undefined,
        reporter: undefined,
        urgency: undefined,
        faultType: undefined,
        reportType: undefined,
        description: undefined,
        status: 'DRAFT'
      },
      images: []
      ,equipmentTypes: []
      ,reportTypes: []
      ,faultTypes: []
      ,urgencyLevels: []
      ,selectorVisible: false
      ,selectedAssets: []
      ,allowEditBasic: true
      ,draftExists: false
      ,pickerOptions: {
        // 禁用今天之后的日期
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      }
      ,basicRules: {
        assetNo: [
          { required: true, message: '请选择资产', trigger: 'change' }
        ]
      }
      ,rules: {
        occurTime: [
          { required: true, message: '请选择发生时间', trigger: 'change' },
          {
            validator: this.validateOccurTime,
            trigger: 'change'
          }
        ],
        reporter: [
          { required: true, message: '请输入报修人', trigger: 'blur' }
        ],
        urgency: [
          { required: true, message: '请选择紧急程度', trigger: 'change' }
        ],
        reportType: [
          { required: true, message: '请选择报修类型', trigger: 'change' }
        ],
        faultType: [
          { required: true, message: '请选择故障类型', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入故障描述', trigger: 'blur' }
        ]
      }
    }
  },
  async created() {
    const { orderNo } = this.$route.params
    // 默认用当前登录用户名填充报修人
    try {
      const currentUserName = (store && store.getters && store.getters.name) || ''
      if (!this.form.reporter) {
        this.form.reporter = currentUserName
      }
    } catch(e) {}
    
    // 先加载字典数据
    await this.loadDictionaries()
    
    if (orderNo) {
      // 查看/编辑已有报修时，基础信息仍允许编辑：根据你的需求可切换为 false
      this.allowEditBasic = true
      // 确保字典数据加载完成后再加载编辑数据
      await this.loadEditData(orderNo)
    }
    // 加载本地草稿
    try {
      const key = this.draftKey()
      const raw = localStorage.getItem(key)
      this.draftExists = !!raw
    } catch(e) {}
  },
  methods: {
    handleOccurTimeChange(value) {
      this.validateOccurTime(null, value, () => {});
    },

    validateOccurTime(rule, value, callback) {
      if (!value) {
        callback(new Error('请选择发生时间'));
        return;
      }

      const selectedTime = new Date(value);
      const now = new Date();

      if (selectedTime > now) {
        // 如果选择的日期超过当前时间，清除并提示
        this.form.occurTime = new Date();
        callback(new Error('发生时间不能晚于当前时间，请重新选择'));
      } else {
        callback();
      }
    },

    draftKey() {
      const id = (this.form && this.form.reportNo) || (this.$route && this.$route.params && this.$route.params.orderNo) || 'new'
      return `fault-report-draft:${id}`
    },
    async loadDictionaries() {
      try {
        // 使用统一的字典加载器
        const dictionaries = await loadRepairDictionaries()
        
        // 设置字典数据
        this.equipmentTypes = dictionaries.equipmentTypes || []
        this.reportTypes = dictionaries.reportTypes || []
        this.faultTypes = dictionaries.faultTypes || []
        this.urgencyLevels = dictionaries.urgencyLevels || []
      } catch (error) {
        console.error('加载字典数据失败:', error)
        // 设置默认空数组，避免undefined错误
        this.equipmentTypes = []
        this.reportTypes = []
        this.faultTypes = []
        this.urgencyLevels = []
      }
    },

    // 加载编辑数据
    async loadEditData(orderNo) {
      try {
        const res = await getOrder(orderNo)
        const d = res.data || {}
        
        // 设置表单数据
        this.form = { ...this.form, ...d }
        this.form.reportNo = d.reportNo || this.form.reportNo
        
        // 映射字段：后端 assetType -> 前端 type；faultDescription -> description
        this.form.type = d.assetType || this.form.type
        this.form.description = d.faultDescription || this.form.description
        
        // 处理图片数据
        const urls = d.imageUrls ? JSON.parse(d.imageUrls) : []
        this.$nextTick(() => this.$refs.imageUpload && this.$refs.imageUpload.initFromUrls(urls))
        
        // 根据资产编号再校准联动字段
        this.handleAssetNoChange()
      } catch (error) {
        console.error('加载编辑数据失败:', error)
        this.$message.error('加载数据失败，请重试')
      }
    },
    // 资产编号填入后自动带出 类型/名称/部门/位置
    handleAssetNoChange() {
      const no = (this.form.assetNo || '').trim()
      if (!no) return
      getAsset(no).then(res => {
        const a = res.data || {}
        this.form.assetName = a.assetName || a.name || ''
        this.form.type = a.equipmentTypeCode || ''
        this.form.deptId = a.deptId || ''
        this.form.location = a.location || ''
      })
    },
    // 打开资产选择器
    openAssetSelector() {
      this.selectorVisible = true
    },
    
    // 选择资产回调（从组件返回）
    onSelectAssets(list) {
      this.selectorVisible = false
      const first = (list && list[0]) || null
      if (first) {
        this.form.assetNo = first.assetNo
        this.form.assetName = first.assetName || first.name
        this.form.type = first.equipmentTypeCode
        this.form.deptId = first.deptId
        this.form.location = first.location
        
        // 不再需要额外的重复检查，AssetSelector已经通过UI状态控制
      }
    },
    
    goBack() {
      // 返回到进入前的列表：优先 /order，其次 /system/order/index，最后按当前上下文选择默认
      const views = (this.$store && this.$store.state && this.$store.state.tagsView && this.$store.state.tagsView.visitedViews) || []
      const prefer = views.find(v => v.path === '/order') || views.find(v => v.path === '/system/order/index')
      const defaultPath = (this.$route && this.$route.path && this.$route.path.indexOf('/order') === 0)
        ? '/order'
        : '/system/order/index'
      const target = prefer ? { path: prefer.fullPath || prefer.path } : { path: defaultPath }
      if (this.$tab && this.$tab.closeOpenPage) {
        this.$tab.closeOpenPage(target)
      } else {
        this.$router.push(target)
      }
    },
    // 临时保存（草稿）到 localStorage
    tempSave() {
      try {
        const key = this.draftKey()
        const payload = {
          form: this.form,
          images: this.images,
          time: Date.now()
        }
        localStorage.setItem(key, JSON.stringify(payload))
        this.draftExists = true
        this.$message.success('草稿已保存到本地')
      } catch(e) {
        this.$message.error('草稿保存失败')
      }
    },
    // 恢复草稿
    restoreDraft() {
      try {
        const key = this.draftKey()
        const raw = localStorage.getItem(key)
        if (!raw) return this.$message.info('暂无草稿')
        const obj = JSON.parse(raw)
        this.form = { ...this.form, ...(obj.form || {}) }
        this.images = obj.images || []
        // 如果组件存在初始化方法，进行同步
        this.$nextTick(() => this.$refs.imageUpload && this.$refs.imageUpload.initFromUrls(this.images.map(i => i.rawName || i.url)))
        this.$message.success('草稿已恢复')
      } catch(e) {
        this.$message.error('草稿恢复失败')
      }
    },
    async submit() {
      // 先进行表单验证
      try {
        await this.$refs.basicFormRef.validate()
        await this.$refs.faultFormRef.validate()
      } catch (error) {
        this.$message.error('请填写完整的基本信息和故障信息')
        return
      }

      // 直接提交，AssetSelector已经通过UI状态控制重复选择
      this.doSubmit()
    },

    doSubmit() {
      const payload = { ...this.form, imageUrls: JSON.stringify(this.images.map(i => i.rawName || i.url)) }
      // 字段映射：前端字段 -> 后端字段
      payload.assetType = this.form.type || payload.assetType
      payload.faultDescription = this.form.description || payload.faultDescription

      // 根据编码查找对应的中文名称
      if (payload.urgency) {
        const urgencyItem = this.urgencyLevels.find(item => item.code === payload.urgency)
        payload.urgencyName = urgencyItem ? urgencyItem.name : ''
      }
      if (payload.reportType) {
        const reportTypeItem = this.reportTypes.find(item => item.code === payload.reportType)
        payload.reportTypeName = reportTypeItem ? reportTypeItem.name : ''
      }
      if (payload.faultType) {
        const faultTypeItem = this.faultTypes.find(item => item.code === payload.faultType)
        payload.faultTypeName = faultTypeItem ? faultTypeItem.name : ''
      }

      // 处理部门字段：deptId存储部门信息，deptName存储部门名称
      if (payload.deptId) {
        // 如果deptId有值，将其作为部门名称存储到deptName
        payload.deptName = payload.deptId
      }

      const fn = this.form.reportNo ? updateOrder : addOrder
      fn(payload).then(() => {
        this.$message.success('提交成功')
        // 提交成功后清理本地草稿
        try { localStorage.removeItem(this.draftKey()) } catch(e) {}
        // 关闭编辑标签并返回列表：优先 /order，其次 /system/order/index
        const views = (this.$store && this.$store.state && this.$store.state.tagsView && this.$store.state.tagsView.visitedViews) || []
        const prefer = views.find(v => v.path === '/order') || views.find(v => v.path === '/system/order/index')
        const defaultPath = (this.$route && this.$route.path && this.$route.path.indexOf('/order') === 0)
          ? '/order'
          : '/system/order/index'
        const target = prefer ? { path: prefer.fullPath || prefer.path } : { path: defaultPath }
        if (this.$tab && this.$tab.closeOpenPage) {
          this.$tab.closeOpenPage(target)
        } else {
          this.$router.push(target)
        }
      }).catch(err => {
        console.error('提交失败:', err)
        this.$message.error('提交失败: ' + (err.message || '未知错误'))
      })
    }
  }
}
</script>


